package zcw.com.lib_leet_code;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by 朱城委 on 2021/8/23.<br><br>
 *
 * 中等：跳跃游戏 III
 */
public class Topic1306 {

    public static void main(String[] args) {
        Topic1306 instance = new Topic1306();

        int[] array = new int[] {4,2,3,0,3,1,2};
        System.out.println(instance.canReach(array, 5));

        array = new int[] {4,2,3,0,3,1,2};
        System.out.println(instance.canReach(array, 0));

        array = new int[] {3,0,2,1,2};
        System.out.println(instance.canReach(array, 2));

        array = new int[] {0,1};
        System.out.println(instance.canReach(array, 1));
    }

    public boolean canReach(int[] arr, int start) {
        if(arr[start] == 0) {
            return true;
        }

        Queue<Integer> queue = new LinkedList<>();
        queue.add(start);

        while (!queue.isEmpty()) {
            int index = queue.poll();

            if(arr[index] == 0) {
                return true;
            }

            if(arr[index] < 0) {
                continue;
            }

            int temp = index + arr[index];
            if(temp < arr.length) {
                queue.add(temp);
            }

            temp = index - arr[index];
            if(temp >= 0) {
                queue.add(temp);
            }

            arr[index] = -arr[index];
        }

        return false;
    }

    public boolean canReach3(int[] arr, int start) {
        return helper(arr, start);
    }

    private boolean helper(int[] arr, int index) {
        if(index < 0 || index >= arr.length || arr[index] >= arr.length) {
            return false;
        }

        int temp = arr[index];
        arr[index] += arr.length;
        return temp == 0 || helper(arr, index + temp) || helper(arr, index - temp);
    }

    public boolean canReach2(int[] arr, int start) {
        if(arr[start] == 0) {
            return true;
        }

        boolean[] used = new boolean[arr.length];
        Queue<Integer> queue = new LinkedList<>();

        used[start] = true;
        queue.offer(start);

        while (!queue.isEmpty()) {
            int index = queue.poll();

            if(arr[index] == 0) {
                return true;
            }

            int temp = index + arr[index];
            if(temp < arr.length && !used[temp]) {
                if(arr[temp] == 0) {
                    return true;
                }

                used[temp] = true;
                queue.offer(temp);
            }

            temp = index - arr[index];
            if(temp >= 0 && !used[temp]) {
                if(arr[temp] == 0) {
                    return true;
                }

                used[temp] = true;
                queue.offer(temp);
            }
        }

        return false;
    }
}
